let monitoringInterval;
let isMonitoring = false;
let previousStocks = new Set();
let showOnlyGEM = false; // 是否只显示创业板
let showOnlyKCB = false; // 是否只显示科创板
let showOnlyMain = false; // 是否只显示主板
let showOnlyBJ = false; // 是否只显示北交所
let showOnlyST = false; // 是否只显示ST股票
let currentStocks = []; // 保存当前的股票数据

// 概念监控相关变量
let gainianMonitoringInterval;
let isGainianMonitoring = false;
// 历史记录功能
const MAX_HISTORY = 10;

// 添加变量跟踪最后点击时间
let lastGainianSubmitTime = 0;

// 排序相关变量
let currentSortField = null;
let currentSortDirection = 'desc'; // 'asc' 或 'desc'

// 股票筛选函数
function filterStocks(stocks) {
    return stocks.filter(stock => {
        // 如果没有任何筛选条件，返回所有股票
        if (!showOnlyGEM && !showOnlyKCB && !showOnlyMain && !showOnlyBJ && !showOnlyST) {
            return true;
        }
        
        // 创业板筛选 (30开头)
        if (showOnlyGEM && stock.code.startsWith('30')) {
            return true;
        }
        
        // 科创板筛选 (688开头)
        if (showOnlyKCB && stock.code.startsWith('688')) {
            return true;
        }
        
        // 主板筛选 (60开头的上海主板，00开头的深圳主板，但排除002开头的中小板)
        if (showOnlyMain && (
            stock.code.startsWith('60') || 
            (stock.code.startsWith('00') && !stock.code.startsWith('002'))
        )) {
            return true;
        }
        
        // 北交所筛选 (8开头或43开头)
        if (showOnlyBJ && (stock.code.startsWith('8') || stock.code.startsWith('43'))) {
            return true;
        }
        
        // ST股票筛选 (名称包含ST)
        if (showOnlyST && stock.name && stock.name.includes('ST')) {
            return true;
        }
        
        return false;
    });
}

function saveToHistory(key, value) {
    if (!value.trim()) return;

    let history = JSON.parse(localStorage.getItem(key) || '[]');
    // 移除重复项
    history = history.filter(item => item !== value);
    // 添加到开头
    history.unshift(value);
    // 保持最大数量
    if (history.length > MAX_HISTORY) {
        history = history.slice(0, MAX_HISTORY);
    }
    localStorage.setItem(key, JSON.stringify(history));
    updateHistoryDropdown(key);
}

function updateHistoryDropdown(key) {
    const history = JSON.parse(localStorage.getItem(key) || '[]');
    const dropdownId = key === 'focusStocksHistory' ? 'focusStocksHistory' : 'iwencaiHistory';
    const inputId = key === 'focusStocksHistory' ? 'focusStocks' : 'iwencaiKeyword';
    const dropdown = $(`#${dropdownId}`);

    if (history.length === 0) {
        dropdown.hide();
        return;
    }

    dropdown.empty();
    history.forEach(item => {
        const historyItem = $('<div>')
            .addClass('history-item')
            .text(item)
            .click(function () {
                $(`#${inputId}`).val(item);
                dropdown.hide();
            });
        dropdown.append(historyItem);
    });
}

// 为输入框添加焦点事件
$('#focusStocks, #iwencaiKeyword').on('focus', function () {
    const key = this.id === 'focusStocks' ? 'focusStocksHistory' : 'iwencaiHistory';
    updateHistoryDropdown(key);
    $(`#${key}`).show();
});

// 点击其他地方时隐藏历史记录
$(document).click(function (e) {
    if (!$(e.target).closest('.input-group').length) {
        $('.history-dropdown').hide();
    }
});

function toggleMonitoring() {
    if (isMonitoring) {
        stopMonitoring();
    } else {
        startMonitoring();
    }
}

function startMonitoring() {
    const focusStocks = $('#focusStocks').val().trim();
    const iwencaiKeyword = $('#iwencaiKeyword').val().trim();
    const interval = parseInt($('#checkInterval').val().trim()) || 60;

    if (!focusStocks) {
        alert('请输入要监控的股票代码');
        return;
    }

    if (!iwencaiKeyword) {
        alert('请输入提示词');
        return;
    }

    // 检查输入的股票代码格式
    const stockLines = focusStocks.split('\n').map(s => s.trim()).filter(s => s);
    if (stockLines.length === 0) {
        alert('请至少输入一个股票代码');
        return;
    }

    // 验证每个股票代码必须是6位数字
    const invalidCodes = stockLines.filter(code => !/^\d{6}$/.test(code));
    if (invalidCodes.length > 0) {
        alert(`以下股票代码格式错误（必须是6位数字）：\n${invalidCodes.join('\n')}`);
        return;
    }

    // 保存到历史记录
    saveToHistory('focusStocksHistory', focusStocks);
    saveToHistory('iwencaiHistory', iwencaiKeyword);

    if (monitoringInterval) {
        clearInterval(monitoringInterval);
    }

    // 清空之前的股票记录
    previousStocks.clear();

    // 添加一个标志位来防止重复请求
    let isRequesting = false;

    // 创建一个包装函数来处理请求
    const doCheck = () => {
        if (isRequesting) return;
        
        // 检查是否在监控时间段内
        if (window.isInMonitoringTime && !window.isInMonitoringTime()) {
            console.log('当前不在监控时间段内，跳过本次检查');
            return;
        }
        
        isRequesting = true;

        checkStocksWithIwencai(focusStocks, iwencaiKeyword)
            .finally(() => {
                isRequesting = false;
            });
    };

    // 立即执行一次
    doCheck();

    // 设置定时器
    monitoringInterval = setInterval(doCheck, interval * 1000);

    isMonitoring = true;
    updateMonitoringStatus();
    $('#monitorBtn').text('停止监控').removeClass('btn-primary').addClass('btn-danger');
    $('#checkInterval, #iwencaiKeyword').prop('disabled', true);
}

// 排序功能实现
function setupSortListeners() {
    $('.sortable').click(function() {
        const sortField = $(this).data('sort');
        
        // 如果点击的是当前排序字段，切换排序方向
        if (currentSortField === sortField) {
            currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            // 如果是新字段，默认降序
            currentSortField = sortField;
            currentSortDirection = 'desc';
        }
        
        // 更新排序图标
        updateSortIcons();
        
        // 显示清除排序按钮和更新状态
        updateSortStatus();
        
        // 重新渲染表格
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 清除排序按钮事件
    $('#clearSortBtn').click(function() {
        clearSort();
    });
}

function updateSortIcons() {
    // 清除所有排序样式
    $('.sortable').removeClass('sort-asc sort-desc');
    
    // 为当前排序字段添加样式
    if (currentSortField) {
        $(`.sortable[data-sort="${currentSortField}"]`).addClass(`sort-${currentSortDirection}`);
    }
}

function sortStocks(stocks) {
    if (!currentSortField || !stocks || stocks.length === 0) {
        return stocks;
    }
    
    return stocks.sort((a, b) => {
        let valueA, valueB;
        
        switch (currentSortField) {
            case 'price':
                valueA = parseFloat(a.price) || 0;
                valueB = parseFloat(b.price) || 0;
                break;
            case 'changePercent':
                valueA = parseFloat(a.changePercent) || 0;
                valueB = parseFloat(b.changePercent) || 0;
                break;
            case 'gainian':
                valueA = a.gainian || '';
                valueB = b.gainian || '';
                // 对于文本字段，使用本地化字符串比较
                return currentSortDirection === 'asc' ? 
                    valueA.localeCompare(valueB, 'zh-CN') : 
                    valueB.localeCompare(valueA, 'zh-CN');
            case 'flows':
                // 处理主力流入，可能包含单位(万、亿)
                valueA = parseFlowValue(a.flows);
                valueB = parseFlowValue(b.flows);
                break;
            case 'hots':
                valueA = parseHotsValue(a.hots);
                valueB = parseHotsValue(b.hots);
                break;
            default:
                return 0;
        }
        
        // 数值比较
        if (currentSortDirection === 'asc') {
            return valueA - valueB;
        } else {
            return valueB - valueA;
        }
    });
}

function parseFlowValue(flowStr) {
    if (!flowStr || flowStr === '-') return 0;
    
    // 移除非数字字符，但保留负号和小数点
    let numStr = flowStr.replace(/[^\d.-]/g, '');
    let value = parseFloat(numStr) || 0;
    
    // 处理单位
    if (flowStr.includes('亿')) {
        value *= 100000000;
    } else if (flowStr.includes('万')) {
        value *= 10000;
    }
    
    return value;
}

function parseHotsValue(hotsStr) {
    if (!hotsStr) return 0;
    
    // 如果整个值就是 '-'，返回 999
    if (hotsStr === '-') return 999;
    
    // 如果是数组格式 [-,-,374] 或 [1,2,374]
    if (hotsStr.includes('[') && hotsStr.includes(']')) {
        // 提取方括号内的内容
        const match = hotsStr.match(/\[([^\]]+)\]/);
        if (match) {
            const arrayContent = match[1];
            // 按逗号分割并获取最后一个元素
            const parts = arrayContent.split(',');
            if (parts.length > 0) {
                const lastValue = parts[parts.length - 1].trim();
                // 如果最后一个值是 '-'，返回 999
                if (lastValue === '-') {
                    return 999;
                }
                // 否则解析为数字
                return parseInt(lastValue) || 0;
            }
        }
    }
    
    // 如果不是数组格式，直接解析为整数
    return parseInt(hotsStr) || 0;
}

// 新增函数：格式化热度榜显示，检测下降趋势
function formatHotsDisplay(hotsStr) {
    // alert("======+"+hotsStr);
    if (!hotsStr || hotsStr === '-') {
        return hotsStr;
    }
    // 如果是数组格式，检测下降趋势
    if (hotsStr.includes('[') && hotsStr.includes(']')) {
        const match = hotsStr.match(/\[([^\]]+)\]/);
        if (match) {
            const arrayContent = match[1];
            const parts = arrayContent.split(',').map(s => s.trim());
            
            // 如果数组长度大于1，检查是否有下降趋势
            if (parts.length > 1) {
                // 过滤掉 '-' 并转换为数字，保持原位置信息
                const numbers = [];
                for (let i = 0; i < parts.length; i++) {
                    if (parts[i] !== '-' && !isNaN(parseInt(parts[i]))) {
                        numbers.push({
                            value: parseInt(parts[i]),
                            index: i
                        });
                    }
                }
                
                // 如果有至少2个有效数字，检查最后一个是否比前一个小
                if (numbers.length >= 3) {
                    const lastNumber = numbers[2];
                    // const secondLastNumber = numbers[numbers.length - 2];
                    if (lastNumber.value >0) {
                        // 检测到下降趋势，添加红色下降箭头
                        return hotsStr + ' <span class="hot-rank-declining">↑</span>';
                    }else {
                        return hotsStr + ' <span class="green-rank-declining">↓</span>';
                    }
                }
            }
        }
    }
    
    return hotsStr;
}

function checkStocksWithIwencai(focusStocks, iwencaiKeyword) {
    // 显示加载指示器
    $('#loadingIndicator').addClass('active');

    // 返回Promise以便处理请求状态
    return new Promise((resolve, reject) => {
        // 发送组合请求到后端
        $.ajax({
            url: '/api/iwencai/monitor',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                focusStocks: focusStocks,
                iwencaiKeyword: iwencaiKeyword
            }),
            success: function (response) {
                updateStockTable(response.stocks, response.totalCount, response.gainian);
                // 隐藏加载指示器
                $('#loadingIndicator').removeClass('active');
                resolve(response);
            },
            error: function (xhr, status, error) {
                console.error('监控请求失败:', error);
                alert('监控请求失败，请检查网络连接');
                stopMonitoring();
                // 出错时也要隐藏加载指示器
                $('#loadingIndicator').removeClass('active');
                reject(error);
            }
        });
    });
}

function updateStockTable(stocks, totalCount, gainian) {
    // 清空表格
    $('#stockTableBody').empty();
    // 保存当前的股票数据
    currentStocks = stocks || [];
    // 如果没有新数据，直接返回
    if (!stocks || stocks.length === 0) {
        $('#matchCount').text('0');
        $('#totalCount').text('0');
        // 更新统计数据和图表（空数据）
        if (typeof updateStatsAndCharts === 'function') {
            updateStatsAndCharts([]);
        }
        return;
    }
// 更新热门概念文本框
    if (gainian) {
        // 计算每个概念的股票数量
        const gainianCount = {};
        stocks.forEach(stock => {
            if (stock.gainian) {
                const gainianList = stock.gainian.split(',');
                gainianList.forEach(g => {
                    g = g.trim();
                    gainianCount[g] = (gainianCount[g] || 0) + 1;
                });
            }
        });

        // 转换成数组并排序
        const sortedGainian = gainian.map(g => ({
            name: g.name,
            count: gainianCount[g.name] || 0
        })).sort((a, b) => b.count - a.count);

        const gainianNames = sortedGainian.map(g => `${g.name}(${g.count})`);
        $('#hotGainian').val(gainianNames.join(','));
    }
    // 根据筛选条件筛选股票
    stocks = filterStocks(currentStocks);

    // 更新统计数据和图表
    if (typeof updateStatsAndCharts === 'function') {
        updateStatsAndCharts(stocks);
    }

    let tbody = $('#stockTableBody');

    // 按类型过滤股票
    const type0Stocks = stocks.filter(stock => stock.type >= 1); // 重点关注
    const type1Stocks = stocks.filter(stock => stock.type === 1); // 重点关注
    const type2Stocks = stocks.filter(stock => stock.type === 2); // 新出现
    const type3Stocks = stocks.filter(stock => stock.type === 3); // 洗盘
    const type4Stocks = stocks.filter(stock => stock.type === 4); // 连续
    const gainianStocks = stocks.filter(stock => stock.gainian && stock.gainian !== '-'); // 有概念的股票

    // 获取所有复制按钮
    const copyType0Btn = $('#copyType0Btn');
    const copyType1Btn = $('#copyType1Btn');
    const copyType2Btn = $('#copyType2Btn');
    const copyType3Btn = $('#copyType3Btn');
    const copyType4Btn = $('#copyType4Btn');
    const copyGainianBtn = $('#copyGainianBtn');

    // 更新重点关注股票复制按钮
    if (copyType0Btn.length > 0) {
        copyType0Btn.show();
        copyType0Btn.off('click').on('click', function () {
            const codes = type0Stocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyType0Btn.text();
            copyType0Btn.text(`已复制 ${type1Stocks.length} 个股票!`);
            setTimeout(() => {
                copyType0Btn.text(originalText);
            }, 1500);
        });
    } else {
        copyType0Btn.hide();
    }

    // 更新重点关注股票复制按钮
    if (type1Stocks.length > 0) {
        copyType1Btn.show();
        copyType1Btn.off('click').on('click', function () {
            const codes = type1Stocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyType1Btn.text();
            copyType1Btn.text(`已复制 ${type1Stocks.length} 个重点关注股票!`);
            setTimeout(() => {
                copyType1Btn.text(originalText);
            }, 1500);
        });
    } else {
        copyType1Btn.hide();
    }

    // 更新新出现股票复制按钮
    if (type2Stocks.length > 0) {
        copyType2Btn.show();
        copyType2Btn.off('click').on('click', function () {
            const codes = type2Stocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyType2Btn.text();
            copyType2Btn.text(`已复制 ${type2Stocks.length} 个新出现股票!`);
            setTimeout(() => {
                copyType2Btn.text(originalText);
            }, 1500);
        });
    } else {
        copyType2Btn.hide();
    }

    // 更新洗盘股票复制按钮
    if (type3Stocks.length > 0) {
        copyType3Btn.show();
        copyType3Btn.off('click').on('click', function () {
            const codes = type3Stocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyType3Btn.text();
            copyType3Btn.text(`已复制 ${type3Stocks.length} 个洗盘股票!`);
            setTimeout(() => {
                copyType3Btn.text(originalText);
            }, 1500);
        });
    } else {
        copyType3Btn.hide();
    }

    // 更新连续股票复制按钮
    if (type4Stocks.length > 0) {
        copyType4Btn.show();
        copyType4Btn.off('click').on('click', function () {
            const codes = type4Stocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyType4Btn.text();
            copyType4Btn.text(`已复制 ${type4Stocks.length} 个连续股票!`);
            setTimeout(() => {
                copyType4Btn.text(originalText);
            }, 1500);
        });
    } else {
        copyType4Btn.hide();
    }

    // 更新概念股票复制按钮
    if (gainianStocks.length > 0) {
        copyGainianBtn.show();
        copyGainianBtn.off('click').on('click', function () {
            const codes = gainianStocks.map(stock => stock.code).join(',');
            copyToClipboard(codes);
            const originalText = copyGainianBtn.text();
            copyGainianBtn.text(`已复制 ${gainianStocks.length} 个概念股票!`);
            setTimeout(() => {
                copyGainianBtn.text(originalText);
            }, 1500);
        });
    } else {
        copyGainianBtn.hide();
    }

    if (stocks && stocks.length > 0) {
        // 如果有用户自定义排序，使用自定义排序；否则使用默认的类型排序
        if (currentSortField) {
            stocks = sortStocks(stocks);
        } else {
            // 对stocks进行排序，按照type分组，优先级：重点关注(1) > 新出现(2) > 洗盘(3) > 连续(4) > 普通(0)
            stocks.sort((a, b) => {
                // 定义类型优先级
                const typePriority = {
                    1: 0, // 重点关注最优先
                    2: 1, // 新出现第二
                    3: 2, // 洗盘第三
                    4: 3, // 连续第四
                    0: 4  // 普通股票最后
                };

                // 首先按照类型优先级排序
                const priorityDiff = typePriority[a.type] - typePriority[b.type];
                if (priorityDiff !== 0) return priorityDiff;

                // 同类型内部按照涨跌幅排序（可选）
                return parseFloat(b.changePercent) - parseFloat(a.changePercent);
            });
        }

        stocks.forEach(function (stock) {
            let row = $('<tr>');
            // 根据stock.type添加对应的样式类
            row.addClass(`stock-type-${stock.type}`);

            let codeCell = $('<td>');
            let codeText = $('<span>').text(stock.code);
            let copyBtn = $('<button>')
                .addClass('copy-btn')
                .text('复制')
                .attr('data-code', stock.code)
                .click(function () {
                    copyToClipboard($(this).attr('data-code'));
                });
            codeCell.append(codeText).append(copyBtn);
            row.append(codeCell);
            row.append($('<td>').text(stock.name));
            row.append($('<td>').text(stock.price));
            let changeCell = $('<td>').text((stock.changePercent || 0).toFixed(2) + '%')
                .addClass(stock.changePercent >= 0 ? 'up' : 'down');
            row.append(changeCell);
            row.append($('<td>').text(stock.open));
            row.append($('<td>').text(stock.high));
            row.append($('<td>').text(stock.low));

            // alert(stock.code+"========="+stock.gainian);
            // 处理板块单元格，让每个板块都可以点击
            let gainianCell = $('<td>');
            if (stock.gainian && stock.gainian !== '-') {
                const gainianList = (stock.gainian).split(',');
                gainianList.forEach((gainian, index) => {
                    if (index > 0) gainianCell.append(', ');
                    
                    const gainianSpan = $('<span>')
                        .addClass('gainian-clickable')
                        .text(gainian.trim())
                        .attr('data-gainian', gainian.trim())
                        .click(function() {
                            copyStocksByGainian(gainian.trim(),1);
                        });
                    gainianCell.append(gainianSpan);
                });
            } else {
                // gainianCell.text('');
            }

            if (stock.noHotgainian && stock.noHotgainian !== '-') {
                const gainianList = (stock.noHotgainian).split(',');
                gainianList.forEach((gainian, index) => {
                    if (index > 0) gainianCell.append(', ');
                    const gainianSpan = $('<span>')
                        .addClass('nohotgainian-clickable')
                        .text(gainian.trim())
                        .attr('data-gainian', gainian.trim())
                        .click(function() {
                            copyStocksByGainian(gainian.trim(),2);
                        });
                    gainianCell.append(gainianSpan);
                });
            } else {
                // gainianCell.text('');
            }

            row.append(gainianCell);
            
            row.append($('<td>').text(stock.flows || '-'));
            row.append($('<td>').html(formatHotsDisplay(stock.hots || '-')));
            tbody.append(row);
        });

        // 更新计数
        $('#matchCount').text(stocks.length);
        $('#totalCount').text(totalCount || stocks.length);

        // 更新上一次的股票集合
        previousStocks = new Set(stocks.map(stock => stock.code));
    } else {
        tbody.append($('<tr>').append($('<td colspan="11" class="text-center">').text('未找到相关股票')));
        $('#matchCount').text('0');
        $('#totalCount').text('0');
    }
    $('#refreshTime span').text(new Date().toLocaleString());
}

function stopMonitoring() {
    if (monitoringInterval) {
        clearInterval(monitoringInterval);
        monitoringInterval = null;
    }
    isMonitoring = false;
    updateMonitoringStatus();
    $('#monitorBtn').text('开始监控').removeClass('btn-danger').addClass('btn-primary');
    $('#checkInterval, #iwencaiKeyword').prop('disabled', false);
    previousStocks.clear();
}

function updateMonitoringStatus() {
    const statusSpan = $('#monitorStatus span');
    if (isMonitoring) {
        statusSpan.text('监控中').removeClass('bg-secondary').addClass('bg-success');
    } else {
        statusSpan.text('已关闭').removeClass('bg-success').addClass('bg-secondary');
    }
}

function searchStock() {
    const code = $('#stockCode').val().trim();
    if (!code) {
        alert('请输入股票代码');
        return;
    }
    $.get('/search', {code: code}, function (data) {
        updateStockTable(data);
    });
}

// 添加回车键搜索功能
$('#stockCode').keypress(function (e) {
    if (e.which == 13) {
        searchStock();
    }
});

function searchIwencai() {
    const keyword = $('#iwencaiKeyword').val().trim();
    if (!keyword) {
        alert('请输入提示词');
        return;
    }
    $.get('/api/iwencai/search', {keyword: keyword}, function (data) {
        updateStockTable(data.stocks, data.totalCount);
    });
}

// 添加复制功能
function copyToClipboard(text) {
    // 创建一个临时文本区域
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);

    try {
        // 尝试使用现代 Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(function () {
                showCopySuccess(text);
            }).catch(function (err) {
                // 如果 Clipboard API 失败，使用后备方案
                fallbackCopyToClipboard(textArea);
            });
        } else {
            // 如果不支持 Clipboard API，直接使用后备方案
            fallbackCopyToClipboard(textArea);
        }
    } finally {
        // 清理临时文本区域
        document.body.removeChild(textArea);
    }
}

// 后备复制方案
function fallbackCopyToClipboard(textArea) {
    try {
        textArea.select();
        document.execCommand('copy');
        showCopySuccess(textArea.value);
    } catch (err) {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
    }
}

// 显示复制成功提示
function showCopySuccess(text) {
    let btn = $(`button[data-code="${text}"]`);
    if (btn.length > 0) {
        let originalText = btn.text();
        btn.text('已复制!');
        setTimeout(() => {
            btn.text(originalText);
        }, 1000);
    }
}

// 按板块复制股票代码
function copyStocksByGainian(gainianName,type) {
    if (!currentStocks || currentStocks.length === 0) {
        alert('当前没有股票数据');
        return;
    }

    // 筛选出属于指定板块的股票

    const targetStocks = currentStocks.filter(stock => {
        if (type==1) {
            if (!stock.gainian || stock.gainian === '-') return false;
            const gainianList = stock.gainian.split(',').map(g => g.trim());
            return gainianList.includes(gainianName);
        }else{
            if (!stock.noHotgainian || stock.noHotgainian === '-') return false;
            const gainianList = stock.noHotgainian.split(',').map(g => g.trim());
            return gainianList.includes(gainianName);
        }
    });
    
    if (targetStocks.length === 0) {
        alert(`没有找到属于"${gainianName}"板块的股票`);
        return;
    }
    
    // 提取股票代码
    const codes = targetStocks.map(stock => stock.code).join(',');
    
    // 复制到剪贴板
    copyToClipboard(codes);
    
    // 显示成功提示 - 使用简洁的图标提示
    const gainianSpans = $(`span[data-gainian="${gainianName}"]`);
    gainianSpans.each(function() {
        const $span = $(this);
        
        // 添加成功图标，不改变原文本
        const $icon = $('<span class="copy-success-icon">✓</span>');
        $span.append($icon);
        
        // 1.5秒后移除图标
        setTimeout(() => {
            $icon.remove();
        }, 1500);
    });
    
    // 显示整体成功消息
    showGlobalCopyMessage(`已复制板块"${gainianName}"的${targetStocks.length}只股票`);
    
    // 同时在控制台输出详细信息，方便调试
    console.log(`复制了板块"${gainianName}"的${targetStocks.length}只股票:`, codes);
}

// 显示全局复制成功消息
function showGlobalCopyMessage(message) {
    // 移除已存在的消息
    $('.global-copy-message').remove();
    
    // 创建新的消息元素
    const $message = $('<div class="global-copy-message">')
        .text(message)
        .css({
            'position': 'fixed',
            'top': '20px',
            'right': '20px',
            'background-color': '#28a745',
            'color': 'white',
            'padding': '10px 20px',
            'border-radius': '5px',
            'box-shadow': '0 2px 10px rgba(0,0,0,0.2)',
            'z-index': '9999',
            'font-size': '14px',
            'animation': 'slideInRight 0.3s ease-out'
        });
    
    // 添加到页面
    $('body').append($message);
    
    // 3秒后自动移除
    setTimeout(() => {
        $message.fadeOut(300, function() {
            $(this).remove();
        });
    }, 3000);
}

// 格式化日期占位符
function formatWithDate(template) {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hour = now.getHours().toString().padStart(2, '0');
    const minute = now.getMinutes().toString().padStart(2, '0');

    const dayFormat = `${year}年${month}月${day}日`;
    const hourFormat = `${year}年${month}月${day}日${hour}点`;
    const minuteFormat = `${year}年${month}月${day}日${hour}点${minute}分`;

    return template
        .replaceAll('{日}', dayFormat)
        .replaceAll('{时}', hourFormat)
        .replaceAll('{分}', minuteFormat);
}

function openIwencai() {
    const keyword = $('#iwencaiKeyword').val().trim();
    const baseUrl = 'https://www.iwencai.com/unifiedwap/result?querytype=stock&w=';
    const formattedKeyword = formatWithDate(keyword);
    const url = baseUrl + encodeURIComponent(formattedKeyword);
    window.open(url, '_blank');
}
function openGainianIwencai() {
    const keyword = $('#gainianKeyword').val().trim();
    const baseUrl = 'https://www.iwencai.com/unifiedwap/result?querytype=zhishu&w=';
    const formattedKeyword = formatWithDate(keyword);
    const url = baseUrl + encodeURIComponent(formattedKeyword);
    window.open(url, '_blank');
}

function openReduIwencai() {
    const keyword = '昨天热度排行排名,今日热度排行榜';
    const baseUrl = 'https://www.iwencai.com/unifiedwap/result?querytype=stock&w=';
    const formattedKeyword = formatWithDate(keyword);
    const url = baseUrl + encodeURIComponent(formattedKeyword);
    window.open(url, '_blank');
}

function openIwencaiKey(keyword) {
    // const keyword = '热度排行榜，';
    const baseUrl = 'https://www.iwencai.com/unifiedwap/result?querytype=stock&w=';
    const formattedKeyword = formatWithDate(keyword);
    const url = baseUrl + encodeURIComponent(formattedKeyword);
    window.open(url, '_blank');
}

// 页面加载完成后初始化状态
$(document).ready(function () {
    updateMonitoringStatus();
    
    // 设置排序功能监听器
    setupSortListeners();
    
    // 初始化排序状态
    updateSortStatus();
    
    // 添加创业板过滤开关事件处理
    $('#showOnlyGEM').change(function () {
        showOnlyGEM = $(this).prop('checked');
        // 直接使用当前数据重新渲染表格
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 添加科创板过滤开关事件处理
    $('#showOnlyKCB').change(function () {
        showOnlyKCB = $(this).prop('checked');
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 添加主板过滤开关事件处理
    $('#showOnlyMain').change(function () {
        showOnlyMain = $(this).prop('checked');
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 添加北交所过滤开关事件处理
    $('#showOnlyBJ').change(function () {
        showOnlyBJ = $(this).prop('checked');
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 添加ST股票过滤开关事件处理
    $('#showOnlyST').change(function () {
        showOnlyST = $(this).prop('checked');
        updateStockTable(currentStocks, currentStocks.length);
    });
    
    // 添加折叠功能事件处理
    $('#inputControlsCollapse').on('shown.bs.collapse', function () {
        // 展开时调整表格高度
        $('#tableContainer').removeClass('expanded');
        // updateTableHeight(); // 已禁用：表格不再使用独立滚动条
    });
    
    $('#inputControlsCollapse').on('hidden.bs.collapse', function () {
        // 折叠时调整表格高度
        $('#tableContainer').addClass('expanded');
        // updateTableHeight(); // 已禁用：表格不再使用独立滚动条
    });
    
    // 初始化表格高度
    // updateTableHeight(); // 已禁用：表格不再使用独立滚动条
});

// 为focusStocks输入框添加实时验证
$('#focusStocks').on('input', function () {
    const input = $(this);
    const value = input.val();
    const lines = value.split('\n');

    // 过滤出无效的行
    const invalidLines = lines.map((line, index) => {
        const trimmed = line.trim();
        if (trimmed && !/^\d{6}$/.test(trimmed)) {
            return `第${index + 1}行: ${trimmed}`;
        }
        return null;
    }).filter(x => x);

    // 如果有无效的行，显示错误提示
    if (invalidLines.length > 0) {
        input.addClass('is-invalid');
        if (!input.next('.invalid-feedback').length) {
            input.after('<div class="invalid-feedback">股票代码必须是6位数字</div>');
        }
    } else {
        input.removeClass('is-invalid');
        input.next('.invalid-feedback').remove();
    }
});

// 为概念提示词输入框添加焦点事件
$('#gainianKeyword').on('focus', function () {
    const key = 'gainianHistory';
    updateHistoryDropdown(key);
    $(`#${key}`).show();
});

// 提交概念提示词
$('#submitGainianBtn').on('click', function () {
    submitGainianKeyword();
});
function toggleGainianMonitoring() {
    if (isGainianMonitoring) {
        stopGainianMonitoring();
    } else {
        startGainianMonitoring();
    }
}

function startGainianMonitoring() {
    const gainianKeyword = $('#gainianKeyword').val().trim();
    const interval = parseInt($('#gainianInterval').val().trim()) || 300;

    if (!gainianKeyword) {
        alert('请输入概念提示词');
        return;
    }

    // 保存到历史记录
    saveToHistory('gainianHistory', gainianKeyword);

    if (gainianMonitoringInterval) {
        clearInterval(gainianMonitoringInterval);
    }

    // 添加一个标志位来防止重复请求
    let isRequesting = false;

    // 创建一个包装函数来处理请求
    const doCheck = () => {
        if (isRequesting) return;
        
        // 检查是否在监控时间段内
        if (window.isInMonitoringTime && !window.isInMonitoringTime()) {
            console.log('当前不在监控时间段内，跳过本次检查');
            return;
        }
        
        isRequesting = true;

        submitGainianKeyword()
            .finally(() => {
                isRequesting = false;
            });
    };

    // 立即执行一次
    doCheck();

    // 设置定时器
    gainianMonitoringInterval = setInterval(doCheck, interval * 1000);

    isGainianMonitoring = true;
    updateGainianMonitoringStatus();
    $('#gainianMonitorBtn').text('停止监控').removeClass('btn-primary').addClass('btn-danger');
    $('#gainianInterval, #gainianKeyword').prop('disabled', true);
}

function stopGainianMonitoring() {
    if (gainianMonitoringInterval) {
        clearInterval(gainianMonitoringInterval);
        gainianMonitoringInterval = null;
    }
    isGainianMonitoring = false;
    updateGainianMonitoringStatus();
    $('#gainianMonitorBtn').text('开始监控').removeClass('btn-danger').addClass('btn-primary');
    $('#gainianInterval, #gainianKeyword').prop('disabled', false);
}

function updateGainianMonitoringStatus() {
    const status = $('#gainianMonitorStatus .badge');
    if (isGainianMonitoring) {
        status.removeClass('bg-secondary').addClass('bg-success').text('监控中');
    } else {
        status.removeClass('bg-success').addClass('bg-secondary').text('已关闭');
    }
}

function submitGainianKeyword() {
    const currentTime = new Date().getTime();
    if (currentTime - lastGainianSubmitTime < 2000) {
        return Promise.resolve(); // 如果点击太频繁，直接返回
    }
    lastGainianSubmitTime = currentTime;

    const keyword = $('#gainianKeyword').val().trim();
    if (!keyword) {
        return Promise.resolve();
    }

    // 显示加载指示器
    $('#loadingIndicator').addClass('active');

    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/iwencai/gainian',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                gainianKeyword: keyword
            }),
            success: function (response) {
                $('#loadingIndicator').removeClass('active');
                resolve(response);
            },
            error: function (xhr, status, error) {
                console.error('概念查询失败:', error);
                $('#loadingIndicator').removeClass('active');
                reject(error);
            }
        });
    });
}

function clearSort() {
    currentSortField = null;
    currentSortDirection = 'desc';
    
    // 更新排序图标
    updateSortIcons();
    
    // 隐藏清除排序按钮和更新状态
    updateSortStatus();
    
    // 重新渲染表格
    updateStockTable(currentStocks, currentStocks.length);
}

function updateSortStatus() {
    const clearBtn = $('#clearSortBtn');
    const statusText = $('#sortStatus');
    
    if (currentSortField) {
        // 显示清除按钮
        clearBtn.show();
        
        // 更新状态文本
        const fieldNames = {
            'price': '最新价',
            'changePercent': '涨跌幅',
            'gainian': '所属热门板块',
            'flows': '主力流入',
            'hots': '热度榜'
        };
        
        const fieldName = fieldNames[currentSortField] || currentSortField;
        const direction = currentSortDirection === 'asc' ? '升序' : '降序';
        statusText.text(`按${fieldName}${direction}排序`);
    } else {
        // 隐藏清除按钮
        clearBtn.hide();
        
        // 恢复默认状态文本
        statusText.text('按股票类型排序');
    }
}

// 动态调整表格高度 - 已禁用，表格不再使用独立滚动条
function updateTableHeight() {
    // 表格高度现在由页面滚动控制，不再设置max-height
    // const tableContainer = $('#tableContainer');
    // const isCollapsed = !$('#inputControlsCollapse').hasClass('show');
    
    // if (isCollapsed) {
    //     // 折叠状态下，表格占用更多空间
    //     tableContainer.css('max-height', 'calc(100vh - 150px)');
    // } else {
    //     // 展开状态下，表格空间较小
    //     tableContainer.css('max-height', 'calc(100vh - 350px)');
    // }
}